package cn.webwheel.whtml;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;

public class MainFrameIconifiedListener extends WindowAdapter {

    MainFrame mainFrame;

    TrayIcon trayIcon;

    public MainFrameIconifiedListener(MainFrame mainFrame) {
        this.mainFrame = mainFrame;
        trayIcon = new TrayIcon(MainFrame.icon, mainFrame.getTitle());
        setRunning(false);
    }

    @Override
    public void windowIconified(WindowEvent e) {

        trayIcon.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                SystemTray.getSystemTray().remove(trayIcon);
                mainFrame.setVisible(true);
                mainFrame.setState(Frame.NORMAL);
            }
        });
        try {
            SystemTray.getSystemTray().add(trayIcon);
            mainFrame.setVisible(false);
        } catch (AWTException e1) {
            e1.printStackTrace();
        }
    }

    public void setRunning(boolean running) {
        BufferedImage img = running ? MainFrame.icon2 : MainFrame.icon;
        Dimension trayIconSize = SystemTray.getSystemTray().getTrayIconSize();
        if (trayIconSize.width != img.getWidth() || trayIconSize.height != img.getHeight()) {
            BufferedImage img2 = new BufferedImage(trayIconSize.width, trayIconSize.height, BufferedImage.TYPE_INT_ARGB);
            img2.getGraphics().drawImage(img, 0, 0, img2.getWidth(), img2.getHeight(), null);
            img = img2;
        }
        trayIcon.setImage(img);
    }
}
